# -*- coding:utf-8 -*-

import urllib
import urllib2
import socket
import cookielib
# import json
import re
# import os
import time
import datetime
import threading
import StringIO


# global

# username = 'timin1922'
# passwd = 'tangzhimin0122'
# token_list = ''
# debug = True
# # debug = False


class Taobao():

    def __init__(self, config):
        self.agent_1 = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13'
        self.agent_2 = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:20.0) Gecko/20100101 Firefox/20.0'
        self.config = config

    def login(self):
        cj = cookielib.CookieJar()

        post_data = urllib.urlencode(
            {
                'CtrlVersion': '1,0,0,7',
                'TPL_password': self.config['password'],
                'TPL_redirect_url': '',
                'TPL_username': self.config['username'],
                '_tb_token_': '5d7eba30e3b31',
                'action': 'Authenticator',
                'callback': '',
                'css_style': '',
                'event_submit_do_login': 'anything',
                'fc': 2,
                'from': 'tb',
                'from_encoding': '',
                'guf': '',
                'gvfdcname': '',
                'isIgnore': '',
                'llnick': '',
                'loginType': 3,
                'longLogin': 0,
                'minipara': '',
                'minititle': '',
                'need_sign': '',
                'need_user_id': '',
                'not_duplite_str': '',
                'popid': '',
                'poy': '',
                'pstrong': '',
                'sign': '',
                'style': 'default',
                'support': '000001',
                'tid': ''
            }
        )
        path = 'https://login.taobao.com/member/login.jhtml'
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

        opener.addheaders = [('User-agent', self.agent_2)]
        urllib2.install_opener(opener)
        req = urllib2.Request(path, post_data)
        req.addheader = ('Host', 'login.taobao.com')
        req.addheader = ('Referer', 'https://login.taobao.com/member/login.jhtml')
        # req.addheader = ('Content-Length', 414)
        req.addheader = ('Content-Type', 'application/x-www-form-urlencoded')
        # try login
        try:
            conn = urllib2.urlopen(req)
        except HTTPError, e:
            pass  # todo

        # verify login
        conn1 = urllib2.urlopen('http://i.taobao.com/my_taobao.htm')
        html = conn1.read()
        if html.find('class="to-pay"') == -1:
            print 'Login Fail'
        else:
            print 'Login successful'
        
        if self.config['debug']:
            with open('login.html', 'w') as f:
                f.write(html)


    def get_hiden(self, source):
        hiden_data = {}
        for line in source:
            l = line.strip()
            if l:
                if l.startswith('<input type="hidden"'):
                    _l = l.replace(' ', '')  # remove blankspace
                    # get name
                    _l1 = _l[_l.find('name='):]
                    if len(_l1) < 2:
                        _l1 = _l[_l.find('id='):]
                    _name = _l1.split('"')[1]
                    # get value
                    _l2 = _l[_l.find('value='):]
                    _value = _l2.split('"')[1]

                    hiden_data[_name] = _value
        # self.cache_data = hiden_data
        return hiden_data

    def read_cache(self, source):
        hiden_data = {}
        with open(source) as f:
            for line in f:
                l = line.strip()
                if l:
                    if l.startswith('<input type="hidden"'):
                        _l = l.replace(' ', '')  # remove blankspace
                        # get name
                        _l1 = _l[_l.find('name='):]
                        if len(_l1) < 2:
                            _l1 = _l[_l.find('id='):]
                        _name = _l1.split('"')[1]
                        # get value
                        _l2 = _l[_l.find('value='):]
                        _value = _l2.split('"')[1]

                        hiden_data[_name] = _value
        # self.cache_data = hiden_data
        return hiden_data


    def buy_now(self, item_id, quantity=1):
        buy_url = 'http://buy.taobao.com/auction/buy_now.jhtml'
        price = '9.80'

        buy_data = {
            'tb_token': '',
            'item_url_refer': 'OTHER',
            'item_id': item_id,
            'item_id_num': item_id,
            'auction_type': 'b',
            'from': 'item_detail',
            'frm': '',
            'current_price': price,
            'activity': '',
            'auto_post1': '',
            'quantity': quantity,
            'skuId': '',
            'skuInfo': '',
            'buyer_from': '',
            'chargeTypeId': '',
        }

        source = urllib2.Request(buy_url, urllib.urlencode(buy_data))
        conn = urllib2.urlopen(source)
        html = conn.read()

        sio = StringIO.StringIO(html)

        if self.config['debug']:
            with open('buy.html', 'w') as f:
                f.write(html)

        return self.get_hiden(sio)



    def submit_deal(self,item_id, quantity=1):
        submit_url = 'http://buy.taobao.com/auction/buy_now.jhtml'

        data = self.buy_now(item_id, quantity)
        if self.config['debug']:
            print data

        # get the specail name and vaule#########
        specail_name = ''
        specail_value = ''
        for k in data:
            if len(k) > 20:
                specail_name = k
                specail_value = data[k]
        # print specail_name, specail_value
        #
        submit_data = {
            '_tb_token_': '',
            # '_tb_token_': token_list,
            'action': 'buynow/smcRoleBuyNowAction',
            'event_submit_do_buy': '1',
            'skuId': data['skuId'],
            'item_id_num': data['item_id_num'],
            'quantity': data['quantity'],
            'date': data['date'],
            'isCheckCode': data['isCheckCode'],
            'encryptString': data['encryptString'],
            'sid': data['sid'],
            'gmtCreate': data['gmtCreate'],
            'saleWinId': data['saleWinId'],
            specail_name: specail_value,
            'actualPaidFee': '9.80',
            'itemReferCode': 'taobao.com',
            '_fm.seller._0.q': data['quantity'],  # how many to buy
            '_fm.seller._0.w': '',
            '_fm.seller._0.s': '',
            '_fm.seller._0.g': '1111',
            '_fm.seller._0.r': '2222',
            '_fm.seller._0.ro': '',
            'anony_enabled': data['anony_enabled'],
            '_fm.seller._0.u': '',
            '_fm.seller._0.c': '8888'

        }

        source = urllib2.Request(submit_url, urllib.urlencode(submit_data))
        conn1 = urllib2.urlopen(source)

        if self.config['debug']:
            html = conn1.read()
            with open('submit.html', 'w') as f:
                f.write(html)

    def isOnSale(self, url):
        target_1 = 'J_ClickCatcher J_LinkBuy'
        # target_2 = 'J_ClickCatcher J_LinkBuy tb-disabled'
        target_2 = 'class="tb-count">0</span>'
        conn = urllib2.urlopen(url)
        html = conn.read()

        if self.config['debug']:
            with open('isOnSale.html', 'w') as f:
                f.write(html)

        if html.find(target_1) != -1 and html.find(target_2) == -1:  # hava click button and sale quantity is not 0
            return True
        else:
            return False

    def buy(self, item_id, quantity=1):
            # self.buy_now(item_id, quantity)
            self.submit_deal(item_id,quantity)
            print 'buy ~~~~~~'

    def secondKill(self, url, item_id, quantity=1):
        # while True:
        for x in xrange(0, 1):
            try:
                if self.isOnSale(url):
                    if self.config['debug']:
                        print 'On Sale, start to buy'
                    for y in xrange(0, 2):  # if on sale, buy x times
                        t = threading.Thread(target=self.buy, args=([item_id, quantity]))
                        t.start()
                else:
                    if self.config['debug']:
                        print 'Not on sale now, wait 1 second to check'
                    time.sleep(self.config.checkOnSaleTime)
            except Exception, e:
                # raise
                continue



# if __name__ == "__main__":
#     stream = Taobao()
#     stream.login2()
#     print 'login ok'
#     time.sleep(1)

# stream.buy('19306595397')
#     stream.secondKill('http://item.taobao.com/item.htm?id=21381820676', '21381820676', 1)
